package com.tanhua.admin.service;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.admin.interceptor.AdminHolder;
import com.tanhua.admin.mapper.AdminMapper;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import com.tanhua.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //管理员登录，获取token
    public String login(String username, String password, String code, String uuid) {
        //1、判断用户输入的验证码和redis验证码是否一致
        //1.1 获取redis验证码
        String key = "CODE_"+uuid;
        String value = redisTemplate.opsForValue().get(key);
        //1.2 判断redis验证码是否存在，和输入的验证码是否一致
        if(StringUtils.isEmpty(value) || !value.equals(code)) {
            //1.3 当验证码不一致，抛出自定义异常
            throw new BusinessException("验证码错误");
        }
        //1.4 删除redis验证码
        redisTemplate.delete(key);
        //2、根据用户名，查询管理员对象
        QueryWrapper<Admin> qw = new QueryWrapper<>();
        qw.eq("username",username);
        Admin admin = adminMapper.selectOne(qw);
        //3、判断对象是否存在，判断数据库中的密码和的输入的密码是否一致
        //数据库中的密码是加密之后的，
        //将用户登录时输入的密码加密
        password = SecureUtil.md5(password);
        if(admin == null || !admin.getPassword().equals(password)) {
            throw new BusinessException("用户名或者密码错误");
        }
        //4、生成token
        Map tokenMap = new HashMap();
        tokenMap.put("id",admin.getId());
        String token = JwtUtils.getToken(tokenMap);
        //5、返回
        return token;
    }

    //获取管理员信息
    public AdminVo profile() {
        //1、获取当前管理员id
        Long userId = AdminHolder.getUserId();
        //2、调用mapper，根据id查询管理员对象 Admin
        Admin admin = adminMapper.selectById(userId);
        //3、转化为vo
        return AdminVo.init(admin);
    }
}
